import { Injectable, Inject } from '@angular/core';
import { TaskList } from '../domain/index';
import { Observable } from 'rxjs/Observable';
import { HttpClient, HttpHeaders } from '@angular/common/http';

@Injectable()
export class TaskListService {

  // 定义api路径
  private readonly domain = 'taskLists';
  private headers = new HttpHeaders({ 'Content-Type': 'application/json' });
  constructor(
    @Inject('BASE_CONFIG') private config,
    private http: HttpClient) { }

  /**
   * 添加项目
   * @param taskList
   */
  add(taskList: TaskList): Observable<TaskList> {
    const uri = `${this.config.uri}/${this.domain}`;
    return this.http
      .post<TaskList>(uri, JSON.stringify(taskList), { headers: this.headers });
  }
  /**
   * 修改项目
   * @param taskList
   */
  update(taskList: TaskList): Observable<TaskList> {
    const uri = `${this.config.uri}/${this.domain}/${taskList.id}`;
    const toUpdate = {
      name: taskList.name
    };
    return this.http
      // 指定修改的选项
      .patch<TaskList>(uri, JSON.stringify(toUpdate), { headers: this.headers });
  }

  /**
   * 删除项目
   * @param taskList
   */
  del(taskList: TaskList): Observable<TaskList> {
    const uri = `${this.config.uri}/taskLists/${taskList.id}`;
    return this.http.delete(uri).mapTo(taskList);
  }

  get(projectId: string): Observable<Array<TaskList>> {
    const uri = `${this.config.uri}/${this.domain}`;
    return this.http
      .get<Array<TaskList>>(uri, { params: { 'projectId': projectId } });
  }

  /**
   * 拖动更换位置
   * @param src
   * @param target
   */
  swapOrder(src: TaskList, target: TaskList): Observable<TaskList[]> {
    const dragUri = `${this.config.uri}/${this.domain}/${src.id}`;
    const targetUri = `${this.config.uri}/${this.domain}/${target.id}`;
    const drag$ = this.http.patch<TaskList>(dragUri,
      JSON.stringify({ order: target.order }),
      { headers: this.headers });
    const drop$ = this.http.patch<TaskList>(targetUri,
      JSON.stringify({ order: src.order }),
      { headers: this.headers });
    return Observable
      .concat(drag$, drop$)
      .reduce((arrs, list) => [...arrs, list], []);
  }
}
